<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Color extends BaseModel
{
    use HasFactory;
    protected $table = 'color';
    // 允许批量操作的字段
    protected $fillable = ['color','is_del','created_at','updated_at'];

    public function scopeSearch($query,$params)
    {
        if(!empty($params['color_id'])){
            $query->where('id',$params['color_id']);
        }
        if(!empty($params['product_id'])){
            $ids = ProductColor::where('product_id',$params['product_id'])->pluck('color_id')->toArray();
            $query->whereIn('id',$ids);
        }
        $query->where('is_del',$params['is_del']??2);
        return $query;
    }

    public function product(){
        return $this->belongsToMany(Product::class,'product_color','color_id','product_id');
    }
}
